﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Xml.Linq;

using Newtonsoft.Json;

namespace Infrastructure.Utility
{
    public class SerializeUtility
    {

        #region Json序列化|反序列化

        /// <summary>
        /// json序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static String JsonSerialize<T>(T t) {
            return JsonConvert.SerializeObject(t);
        }

        /// <summary>
        /// json反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(String jsonStr) {
            return JsonConvert.DeserializeObject<T>(jsonStr);
        }

        #endregion

        #region Xml序列化|反序列化

        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static String XmlSerialize<T>(T t) {
            if (t == null) return String.Empty;

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (var stream = new MemoryStream()) {
                serializer.Serialize(stream, t);
                var byteData = stream.ToArray();
                return System.Text.Encoding.UTF8.GetString(byteData);
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(String str) {
            var obj = default(T);
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                using (var stream = new MemoryStream())
                {
                    var byteData = System.Text.Encoding.UTF8.GetBytes(str);
                    stream.Write(byteData, 0, byteData.Length);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);
                    obj = (T)serializer.Deserialize(stream);
                }
            }
            catch (Exception ex) { 
                
            }

            return obj;
        }

        #endregion

    }
}
